﻿using AutoUpdate.Log;
using ScannerApp.Common;
using ScannerApp.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using mshtml;
using ScannerApp.Model;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using MaterialDesignThemes;
using System.Text.RegularExpressions;
using ScannerApp.Business;
using static ScannerApp.Common.PopMessageHelper;
using MSXML2;
using System.Threading.Tasks;
using System.IO;

namespace ScannerApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        ScanApp.ScanAppSoapClient sa = new ScanApp.ScanAppSoapClient();
        string checklogin = "";
        string mac = Common.MacAddress.GetMacAddress();
        IniFiles ini = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\ScanAppConfig.INI");

        public MainWindow()
        {
            InitializeComponent();

            // 设置全屏
            this.WindowState = System.Windows.WindowState.Normal;//不显示边框，只显示工作区
            this.WindowStyle = System.Windows.WindowStyle.None;//无边框
            this.ResizeMode = System.Windows.ResizeMode.NoResize;//禁止大小调整

            WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
        }

        bool IsExistApp()
        {

            #region 检测



            string MName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;

            string PName = System.IO.Path.GetFileNameWithoutExtension(MName);

            System.Diagnostics.Process[] myProcess = System.Diagnostics.Process.GetProcessesByName(PName);



            if (myProcess.Length > 1)

            {

                MessageBox.Show("本程序一次只能运行一个实例！", "提示");

                Application.Current.Shutdown();

                return true;

            }

            else return false ;

            #endregion

        }

        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //if (cz.IsChecked == false && mdfx.IsChecked == false && hlfx.IsChecked == false && test.IsChecked == false)
            //{
            //    PopMessageHelper.ShowMessage("必须选择一个有效登录类型...\r\n窗口3秒后关闭...", "WinPro登录提示", 3000, MsgBoxStyle.YellowAlert_OK);
            //    return;
            //}
            //else {

            //}
            Login(checklogin);

        }

        private void close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            MessageBoxResult result = System.Windows.MessageBox.Show("系统是否关闭？", "提示", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();    
                Environment.Exit(0);
            }
            else
            {

            }

        }
        private void Close_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = System.Windows.MessageBox.Show("系统是否关闭？", "提示", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();
                Environment.Exit(0);
            }
            else
            {

            }
        }
        private void Setting_Click(object sender, RoutedEventArgs e)
        { 
            ShowModalDialog(true);
        }
     

        private void tb_1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ShowModalDialog(true);
        }

        private void tb_sz_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            setting window = new setting();
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.ShowDialog();//模式，弹出！

        }

        private void ck_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var window = new Window();//Windows窗体 
            Business.SelectLanguage s = new SelectLanguage();
            window.Content = s;
            window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            window.ShowDialog();//模式，弹出！

        }

        
        void Login(string type)
        {
            DataTable lsdt = sa.GetDatable_hr_employee(userid.Text.Trim(), mac);
            //var rv = SQLLogic.GetDatable_hr_employee(userid.Text.Trim());
            //if (rv.Item1)
            //{
            if (lsdt.Rows.Count > 0)
            {
                publicclass.MacAddress = mac;
                foreach (DataRow dr in lsdt.Rows)
                {
                    publicclass.UserName = dr["name"].ToString();
                    publicclass.UserID = dr["uid"].ToString();
                    publicclass.Id = dr["id"].ToString();
                }
                if (type == "cz")
                {
                    Logger.Instance.WriteLog(publicclass.UserName + "[登录称重]", LogType.Information, "Login");
                    checklogin = "cz";
                    this.Hide();
                    Weighing window = new Weighing();
                    window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    //window.Source = new Uri("Weighing.xaml", UriKind.Relative);
                    // window.ShowDialog();//模式，弹出！
                    window.Show();//无模式，弹出！
                }
                else if (type == "hlfx")
                {
                    Logger.Instance.WriteLog(publicclass.UserName + "[登录活力分析]", LogType.Information, "Login");

                    checklogin = "hlfx";
                    this.Hide();
                    VitalityAnalysis pb = new VitalityAnalysis();
                    //VIT_Form pb = new VIT_Form();
                    pb.Show();
                }
                else if (type == "mdfx")
                {
                    Logger.Instance.WriteLog(publicclass.UserName + "[登录密度分析]", LogType.Information, "Login");

                    checklogin = "mdfx";

                    this.Hide();
                    Density pb = new Density();
                    pb.Show();
                }
                else if (type == "jycj")
                {
                    Logger.Instance.WriteLog(publicclass.UserName + "[登录精液采集]", LogType.Information, "Login");

                    checklogin = "jycj";
                    this.Hide();
                    Collection pb = new Collection();
                    pb.Show();
                }
                else if (type == "xs")
                {
                    Logger.Instance.WriteLog(publicclass.UserName + "[登录稀释]", LogType.Information, "Login");

                    checklogin = "xs";
                    this.Hide();
                    DilutionPLC pb = new DilutionPLC();
                    pb.Show();
                }
                else if (type == "db")
                {
                    Logger.Instance.WriteLog(publicclass.UserName + "[登录打包]", LogType.Information, "Login");

                    checklogin = "db";

                    this.Hide();
                    PackingPLC pb = new PackingPLC();
                    pb.Show();
                }
                else if (type == "test")
                {
                    Logger.Instance.WriteLog(publicclass.UserName + "[登录测试]", LogType.Information, "Login");

                    checklogin = "test";
                    this.Hide();
                    PrintBarCode pb = new PrintBarCode();
                    pb.Show();
                }
                Common.ConfigHelper.SetIni("CheckLogin", checklogin);
                userid.Text = ""; userid.Focus();
            }
            else
            {
                Logger.Instance.WriteLog("错误！无此用户", LogType.Error, "Login");

                UIAction(() =>
                {
                    userid.Text = "";
                  //  tips.Text =
                    tips.SetResourceReference( TextBlock.TextProperty, "ErrorNoUser");
                    //"错误！无此用户...";
                    userid.Focus();
                });
              
               // PopMessageHelper.ShowMessage("错误！无此用户...\r\n窗口3秒后关闭...", "WinPro登录提示", 3000, MsgStyle.RedCritical_OK);
                // MessageBox.Show("错误！无此用户！");
            }
            //}
            //else
            //{
            //    MessageBox.Show("错误！" + rv.Item2);
            //}

        }
        private void userid_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                if (userid.Text.Trim() == "")
                {
                    UIAction(() =>
                    {
                        userid.Text = "";
                        tips.SetResourceReference(TextBlock.TextProperty, "ErrorNoUser");
                       // tips.Text = "错误！无此用户...";
                        userid.Focus();
                    });
                    return;
                }

                this._loading.Visibility = Visibility.Visible;

                //button1.Focus();
                Login(checklogin);
                this._loading.Visibility = Visibility.Collapsed;

            }

        }

        Int32 test(string h_two, string l_two)
        {

               string tow = h_two + l_two;
            int ha = Convert.ToInt32(h_two, 2);
            int a = 0;
            if (h_two.Substring(0,1) == "1")//高位Bit31为1，则补码
            {
                string hr_ = "", lr_ = "";
                for (int hr1 = 0; hr1 < h_two.Length; hr1++)
                {
                    if (h_two.Substring(hr1, 1) == "1") hr_ += "0"; else hr_ += "1";
                }
                for (int lr1 = 0; lr1 < l_two.Length; lr1++)
                {
                    if (l_two.Substring(lr1, 1) == "1") lr_ += "0"; else lr_ += "1";
                }
                a = -Convert.ToInt32(BinaryStrAdd(hr_ + lr_,"1"), 2);
            }
            else
            {
                a = Convert.ToInt32(tow, 2);
            }
            return a;
        }
        static string BinaryStrAdd(string str1, string str2)
        {
            // Ignore Validation...

            string result = string.Empty;

            int len = 0;
            char[] ch1 = str1.Reverse().ToArray();
            char[] ch2 = str2.Reverse().ToArray();

            len = ch1.Length > ch2.Length ? ch1.Length : ch2.Length;
            byte[] b1 = new byte[len];
            byte[] b2 = new byte[len];
            byte[] b3 = new byte[len + 1];
            for (int i = 0; i < ch1.Length; i++)
            {
                b1[i] = Convert.ToByte(ch1[i].ToString());
            }

            for (int i = 0; i < ch2.Length; i++)
            {
                b2[i] = Convert.ToByte(ch2[i].ToString());
            }

            byte carry = 0;
            for (int i = 0; i < len; i++)
            {
                if (i != 0)
                {
                    if (carry == 1)
                    {
                        b3[i] = (byte)(b1[i] + b2[i] + carry);
                    }
                    else
                    {
                        b3[i] = (byte)(b1[i] + b2[i]);
                    }
                }
                else
                {
                    b3[i] = (byte)(b1[i] + b2[i]);
                }

                if (b3[i] == 2)
                {
                    b3[i] = 0;
                    carry = 1;
                }
                else if (b3[i] == 3)
                {
                    b3[i] = 1;
                    carry = 1;
                }
                else
                {
                    carry = 0;
                }
            }

            if (carry == 1)
            {
                b3[len] = 1;
            }

            StringBuilder sb = new StringBuilder();
            for (int i = b3.Length - 1; i >= 0; i--)
            {
                sb.Append(b3[i]);
            }

            result = sb.ToString();
            return result;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
          //int a=  test("1111111111111111","111111111111100");

          //  return;
          
            try
            {
                string langName = "zh-CN";
                string Single = "WebNet";
                try
                {
                    langName = ini.IniReadValue("公司信息", "SelectLanguages"); //Common.ConfigHelper.GetIni("COM", "");

                    Single = ini.IniReadValue("公司信息", "SingleOrNet"); //Common.ConfigHelper.GetIni("COM", "");
                }
                catch { }


                ResourceDictionary langRd = null;
                try
                {
                    //根据名字载入语言文件
                    langRd = Application.LoadComponent(new Uri(@"Languages\" + langName + ".xaml", UriKind.Relative)) as ResourceDictionary;
                }
                catch (Exception e2)
                {
                   // MessageBox.Show(e2.Message);
                }
                if (langRd != null)
                {
                    Application.Current.Resources.MergedDictionaries[0] = langRd;
                }


                if (IsExistApp())
                    return;

                if (Single == "Single")
                {
                    this.Hide();
                    string SelectSinle = ini.IniReadValue("SingleAppSetting", "LoginStyle");
                    if (SelectSinle == "")
                    {
                        SingleSetting ss = new SingleSetting();
                        ss.Show();
                    }
                    else if (SelectSinle == "db")//罐装
                    {
                        this.Hide();
                        SingleBusiness.PackingPLC plc = new SingleBusiness.PackingPLC();
                        plc.Show();

                    }
                    else if (SelectSinle == "xs")//稀释
                    {
                        this.Hide();
                        SingleBusiness.DilutionPLC plc = new SingleBusiness.DilutionPLC();
                        plc.Show();

                    }
                    return;
                }
                //if (!InterfaceEnble())//网络不通
                //    return;
                AutoUpdate.Updater.CheckUpdateStatus();
                //IniFiles ini = new IniFiles(System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\ScanAppConfig.INI");

                string IsInitSet = "N";
                // 方式3
                if (ini.ExistINIFile())
                {
                    try
                    {
                        IsInitSet = ini.IniReadValue("是否初始化", "IsInitSet");
                        checklogin = ini.IniReadValue("登录类型", "LoginStyle"); ;
                    }
                    catch { }
                }

                if (IsInitSet == "N")
                {
                    this.Hide();
                    navigtion nav = new navigtion();
                    nav.Show();

                }
                loadNotice();
                //DataTable noticDt = sa.GetTableNotice("");
                //if (noticDt.Rows.Count > 0)
                //{
                //    for (int i = 0; i < noticDt.Rows.Count; i++)
                //    {
                //        string msg = "";
                //        msg = noticDt.Rows[i]["notice_title"].ToString();
                //        if (i == 0)
                //        {
                //            ntxt1.Text = msg;
                //        }
                //        if (i == 1)
                //        {
                //            n2.Visibility = Visibility.Visible;
                //            ntxt2.Text = msg;
                //        }
                //        if (i == 2)
                //        {
                //            n3.Visibility = Visibility.Visible;
                //            ntxt3.Text = msg;
                //        }
                //        if (i == 3)
                //        {
                //            n4.Visibility = Visibility.Visible;
                //            ntxt4.Text = msg;
                //        }
                //        if (i == 4)
                //        {
                //            n5.Visibility = Visibility.Visible;
                //            ntxt5.Text = msg;
                //        }


                //    }
                //}

                if (mac == "")
                {
                    PopMessageHelper.ShowMessage("MAC地址获取失败！检测网卡是否正常？\r\n窗口3秒后关闭...", "WinPro系统设置提示", 3000, MsgStyle.RedCritical_OK);
                    return;
                }
                string para = "{\"DeviceName\":\"\",\"MacAddress\":\"" + mac + "\",\"UserID\":\"" + userid.Text.Trim() + "\"}";

                DataTable dt = sa.GetLogin(para);
                if (dt == null)
                {
                    navigtion window = new navigtion();
                    window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    window.ShowDialog();//模式，弹出！
                }
                else
                {
                    if (dt.Rows.Count <= 0)
                    {
                        navigtion window = new navigtion();
                        window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        window.ShowDialog();//模式，弹出！
                    }
                    else if (dt.Rows.Count > 0)
                    {

                        foreach (DataRow dr in dt.Rows)
                        {
                            zd.Text = dr["product_name"].ToString();
                            sb.Text = dr["product_name"].ToString();
                            publicclass.DeviceName = dr["product_name"].ToString();
                            publicclass.SystemLogo = dr["sys_logo"].ToString();
                            publicclass.SystemName = dr["sys_name"].ToString();
                              sysname.Text = publicclass.SystemName;
                            string preurl = Common.ConfigHelper.GetEndpointClientAddress("ScanAppSoap"); 
                            Uri uri = new Uri(preurl);
                            string imageurl = uri.Scheme + "://" + uri.Host + "/" + publicclass.SystemLogo;
                            // Console.WriteLine(uri.Host);
                             im_logo.Source = new BitmapImage(new Uri(imageurl));
                            if (checklogin == OperationType.OperationTypes.cz.ToString())
                            {
                               // im_logo.Source = new BitmapImage(new Uri("/icon/dzc.jpg", UriKind.Relative));
                                // new BitmapImage(new Uri("icon/dzc.jpg")); 
                                GetIni();
                            }
                            else if (checklogin == OperationType.OperationTypes.jycj.ToString())
                            {
                                gzz.SetResourceReference(TextBlock.TextProperty, "syszdcj");
                              //  im_logo.Source = new BitmapImage(new Uri("/icon/cj.png", UriKind.Relative));
                                //new BitmapImage(new Uri("icon/cz.jpg"));
                                zt.Text = "OK";
                            }
                            else if (checklogin == OperationType.OperationTypes.hlfx.ToString())
                            {
                                gzz.SetResourceReference(TextBlock.TextProperty, "sysjyfx");
                                zt.Text = "OK";
                            }
                            else if (checklogin == OperationType.OperationTypes.xs.ToString())
                            {
                                gzz.SetResourceReference(TextBlock.TextProperty, "syszdpz");
                                zt.Text = "OK";
                            }
                            else if (checklogin == OperationType.OperationTypes.db.ToString())
                            {
                                gzz.SetResourceReference(TextBlock.TextProperty, "syszdbz");
                                zt.Text = "OK";
                            }
                            else
                            { zt.Text = "OK"; }

                            //zt.Text = "正常连接";zt.Foreground = Brushes.Green;
                            try { scdl.Text = DateTime.Parse(dr["EventDate"].ToString()).ToString("yyyy-MM-dd hh:mm"); } catch { }
                            dlry.Text = dr["name"].ToString();
                            dqsj.Text = DateTime.Today.ToString("yyyy-MM-dd hh:mm");
                        }
                    }
                }
                //userid.Text = "";
                userid.Focus();
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误/Error:"+ex.Message);
            }
        }

        //private void  a1click(object sender, RoutedEventArgs e)
        //{

        //    NavigationWindow sendWindow = new NavigationWindow();
        //    sendWindow.Source = new Uri("publicnotice.xaml", UriKind.Relative); 
        //   sendWindow.ShowDialog();
        //}

        private void GetIni()
        {
            try
            {
                if (ini.ExistINIFile())
                {
                    string Com = ini.IniReadValue("串口设置", "COM"); //Common.ConfigHelper.GetIni("COM", "");
                    string BaudRate = ini.IniReadValue("串口设置", "BaudRate"); //Common.ConfigHelper.GetIni("BaudRate", "");
                    string DataBits = ini.IniReadValue("串口设置", "DataBits");//Common.ConfigHelper.GetIni("DataBits", "");
                    string StopRate = ini.IniReadValue("串口设置", "StopRate");//Common.ConfigHelper.GetIni("StopRate", "");
                    string ParityRate = ini.IniReadValue("串口设置", "ParityRate"); //Common.ConfigHelper.GetIni("ParityRate", "");
                    SerialPort sp = new SerialPort();
                    string PortName = Com;//串口名    默认值第一个
                    int BR = int.Parse(BaudRate);//获取或设置串行 波特率bit/s  默认值9600
                    int DB = int.Parse(DataBits); ;//获取或设置每个字节的标准数据位长度 默认值8
                    StopBits Stop = (StopBits)Convert.ToDouble(StopRate); ;//获取或设置每个字节的标准停止位数    默认值One 

                    Parity ParityBits = Parity.None;//获取或设置奇偶校验检查协议    默认值None
                    ParityBits = ParityRate == "None" ? Parity.None : Parity.Odd;//目前就2个

                    if (sp.IsOpen)//先判断是否打开 
                    { zt.Text = "正常连接"; zt.Foreground = Brushes.Green; sp.Close(); }

                    sp = new SerialPort(PortName, BR, ParityBits, DB, Stop);
                    sp.Open();
                    if (!sp.IsOpen)//再判断是否打开成功
                    { zt.Text = "连接失败"; zt.Foreground = Brushes.Red; sp.Close(); }
                    else { zt.Text = "正常连接"; zt.Foreground = Brushes.Green; sp.Close(); }

                }
            }
            catch
            {
                zt.Text = "连接失败"; zt.Foreground = Brushes.Red;
            }
        }

        private void ntxt1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //if (ntxt1.Tag == "") return;
            // else {
            ViewNotice vn = new ViewNotice();
            vn.ShowDialog();
            //ClearHtml
            // }
        }
        /// <summary>
        /// 公告显示，最多5个，只显示标题
        /// </summary>
        void loadNotice()
        {
            DataTable noticDt = sa.GetLastNotice();
            if (noticDt.Rows.Count > 0)
            {
              string  msg = noticDt.Rows[0]["notice_txt"].ToString();
                ntxt1.Text = msg;

            }
        }

        void UIAction(Action action)//在主线程外激活线程方法
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(App.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(_ => action(), null);
        }

        private void ShowModalDialog(bool bShow)
        {
            this.ModalDialog.IsOpen = bShow;
            // this.MainPanel.IsEnabled = !bShow;
        }
        private void Dlg_BtnOK_Click(object sender, RoutedEventArgs e)
        {
            string pwd = ini.IniReadValue("密码设置", "setting"); ;
            if (TxtBoxInput.Password == pwd)
            {
                TxtBoxInput.Password = "";
                ShowModalDialog(false);
                navigtion window = new navigtion();
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ShowDialog();//模式，弹出！
            }
            else
            {
                tips.SetResourceReference(TextBlock.TextProperty, "ErrorPwd");
             //   tips.Text = "错误！密码错误！";
            }

        }
        private void Dlg_BtnClose_Click(object sender, RoutedEventArgs e)
        {
            ShowModalDialog(false);

        }

 
          public bool InterfaceEnble()
         {
        string url = Common.ConfigHelper.GetEndpointClientAddress("ScanAppSoap");
        XMLHTTP http = new XMLHTTP();
        try
        {
            http.open("GET ", url, false, null, null);  
            http.send(null);
            int iStatus = http.status;
            //如果状态不为200，就是不能调用此接口 
            if (iStatus == 200)
                return true;
        }
        catch (Exception ex)
        {
            //MessageBox.Show("接口调用失败," + ex);
        }

        return false;
    }

        private void TextBlock_Click(object sender, MouseButtonEventArgs e)
        {
            try
            {


                TextBlock btn = e.OriginalSource as TextBlock;
                if (btn.Name == "Back")
                {
                    TxtBoxInput.Password = TxtBoxInput.Password.Substring(0, TxtBoxInput.Password.Length - 1);
                }
                else
                {
                    TxtBoxInput.Password += btn.Text;
                }
               // publicclass.PopNum = TxtBoxInput.Text.Length == 0 ? "0" : TxtBoxInput.Text;
            }
            catch
            {
            }
        }

        private void txtc(object sender, TextChangedEventArgs e)
        {
            //if (userid.Text.Trim() != "") userid.Text = userid.Text.Trim().Replace(DynamicResource userid, "");
        }


        public static void Dellogs()
        {

            Task.Factory.StartNew(() => {
              //  string basePath = AutoUpdate.Updater.Instance.CurrentApplicationDirectory;
                // Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                // basePath = @"C:\APILogs";
              //  if (!Directory.Exists(basePath + "\\Docment"))

                 var path = AppDomain.CurrentDomain.BaseDirectory + "logs\\"; //文件夹路径
                if (!Directory.Exists(path)) return;

                var dyInfo = new DirectoryInfo(path);
                foreach (var feInfo in dyInfo.GetFiles("*.log"))
                {
                    if (feInfo.LastWriteTime < DateTime.Now.AddDays(-7)) feInfo.Delete();
                }
                //Thread.Sleep(1000 * 60 * 60 * 24);//24小时执行一次
                Dellogs();//递归
            });
        }

    }
}
